package com.library.dao;

import com.library.entity.Book;
import com.library.entity.BorrowRecord;
import com.library.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class BorrowRecordDAO {
    public boolean borrowBook(int userId, int bookId) {
        Connection conn = null;
        PreparedStatement pstmt1 = null;
        PreparedStatement pstmt2 = null;
        try {
            conn = DBUtil.getConnection();
            conn.setAutoCommit(false);

            // 更新图书状态为已借出
            String sql1 = "UPDATE books SET status = 1 WHERE id = ? AND status = 0";
            pstmt1 = conn.prepareStatement(sql1);
            pstmt1.setInt(1, bookId);
            int rows1 = pstmt1.executeUpdate();

            if (rows1 > 0) {
                // 添加借阅记录
                String sql2 = "INSERT INTO borrow_records (user_id, book_id, borrow_date, status) VALUES (?, ?, ?, 0)";
                pstmt2 = conn.prepareStatement(sql2);
                pstmt2.setInt(1, userId);
                pstmt2.setInt(2, bookId);
                pstmt2.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
                int rows2 = pstmt2.executeUpdate();

                if (rows2 > 0) {
                    conn.commit();
                    return true;
                }
            }
            conn.rollback();
            return false;
        } catch (SQLException e) {
            try {
                if (conn != null) conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.close(conn, pstmt1, null);
            DBUtil.close(null, pstmt2, null);
        }
    }

    public boolean returnBook(int recordId, int bookId) {
        Connection conn = null;
        PreparedStatement pstmt1 = null;
        PreparedStatement pstmt2 = null;
        try {
            conn = DBUtil.getConnection();
            conn.setAutoCommit(false);

            // 更新图书状态为可借阅
            String sql1 = "UPDATE books SET status = 0 WHERE id = ?";
            pstmt1 = conn.prepareStatement(sql1);
            pstmt1.setInt(1, bookId);
            pstmt1.executeUpdate();

            // 更新借阅记录状态为已归还
            String sql2 = "UPDATE borrow_records SET return_date = ?, status = 1 WHERE id = ?";
            pstmt2 = conn.prepareStatement(sql2);
            pstmt2.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
            pstmt2.setInt(2, recordId);
            pstmt2.executeUpdate();

            conn.commit();
            return true;
        } catch (SQLException e) {
            try {
                if (conn != null) conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.close(conn, pstmt1, null);
            DBUtil.close(null, pstmt2, null);
        }
    }

    public List<BorrowRecord> getBorrowRecordsByUser(int userId) {
        List<BorrowRecord> records = new ArrayList<>();
        String sql = "SELECT * FROM borrow_records WHERE user_id = ? ORDER BY borrow_date DESC";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, userId);
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    records.add(new BorrowRecord(
                        rs.getInt("id"),
                        rs.getInt("user_id"),
                        rs.getInt("book_id"),
                        rs.getTimestamp("borrow_date"),
                        rs.getTimestamp("return_date"),
                        rs.getInt("status")
                    ));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return records;
    }

    public List<BorrowRecord> getAllBorrowRecords() {
        List<BorrowRecord> records = new ArrayList<>();
        String sql = "SELECT * FROM borrow_records ORDER BY borrow_date DESC";
        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                records.add(new BorrowRecord(
                    rs.getInt("id"),
                    rs.getInt("user_id"),
                    rs.getInt("book_id"),
                    rs.getTimestamp("borrow_date"),
                    rs.getTimestamp("return_date"),
                    rs.getInt("status")
                ));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return records;
    }
}    